using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using ManaMaple.Core.HealthChecks;
using Prometheus;
using Microsoft.Extensions.Logging;

namespace ManaMaple.Core.Extensions
{
    /// <summary>
    /// 监控与日志扩展类
    /// </summary>
    public static class MonitoringExtensions
    {
        /// <summary>
        /// 添加监控与日志服务
        /// </summary>
        public static IServiceCollection AddMonitoringServices(this IServiceCollection services)
        {
            // 添加健康检查服务
            services.AddTransient<DatabaseHealthCheck>();
            
            return services;
        }

        /// <summary>
        /// 添加指标监控服务
        /// </summary>
        public static IServiceCollection AddMetrics(this IServiceCollection services)
        {
            // 可以添加自定义指标收集器或其他指标相关配置
            return services;
        }

        /// <summary>
        /// 使用监控中间件
        /// </summary>
        public static IApplicationBuilder UseMonitoring(this IApplicationBuilder app)
        {
            // 添加Prometheus请求计数中间件
            app.UseHttpMetrics();
            
            // 记录未处理异常
            app.Use(async (context, next) =>
            {
                try
                {
                    await next();
                }
                catch (Exception ex)
                {
                    // 获取日志工厂并创建日志记录器
                    var loggerFactory = context.RequestServices.GetRequiredService<ILoggerFactory>();
                    var logger = loggerFactory.CreateLogger("GlobalExceptionHandler");
                    
                    // 记录异常
                    logger.LogError(ex, "未处理的异常：{Message}", ex.Message);
                    
                    // 增加异常计数器
                    Metrics.CreateCounter("manamaple_unhandled_exceptions_total", "未处理异常计数").Inc();
                    
                    // 重新抛出异常，让异常中间件处理
                    throw;
                }
            });
            
            return app;
        }
    }
}